import React, { PureComponent, Suspense } from 'react';
import { connect } from 'dva';
import cls from 'classnames';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { ExtTable } from 'suid';
import { Button, Modal } from 'antd';
import { Loader } from '@/components';
import { constants } from '@/utils';
import ExtAction from './components/ExtAction';
import styles from './index.less';

const CreateModal = React.lazy(() => import('./CreateModal'));
const UpdateModal = React.lazy(() => import('./UpdateModal'));
const ViewModal = React.lazy(() => import('./ViewModal'));

const { PRICE_MANGER_ACTION, SERVER_PATH } = constants;

@connect(({ priceManger, loading }) => ({ priceManger, loading }))
class PriceManger extends PureComponent {
  static tableRef;

  static confirmModal;

  constructor(props) {
    super(props);
    this.state = {};
  }

  reloadData = () => {
    if (this.tableRef) {
      this.tableRef.remoteDataRefresh();
    }
  };

  add = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'priceManger/updateState',
      payload: {
        showCreate: true,
        currentData: null,
      },
    });
  };

  edit = rowData => {
    const { dispatch } = this.props;
    dispatch({
      type: 'priceManger/updateState',
      payload: {
        showUpdate: true,
        currentData: rowData,
      },
    });
  };

  onSave = data => {
    const { dispatch } = this.props;
    dispatch({
      type: 'priceManger/save',
      payload: {
        ...data,
      },
      callback: res => {
        if (res.success) {
          this.handlerCancel(true);
        }
      },
    });
  };

  /** 单据操作 */
  handlerAction = (key, record) => {
    const { dispatch } = this.props;
    switch (key) {
      case PRICE_MANGER_ACTION.VIEW:
        dispatch({
          type: 'priceManger/updateState',
          payload: {
            currentData: record,
            showView: true,
          },
        });
        break;
      case PRICE_MANGER_ACTION.EDIT:
        dispatch({
          type: 'priceManger/updateState',
          payload: {
            currentData: record,
            showUpdate: true,
          },
        });
        break;
      case PRICE_MANGER_ACTION.DELETE:
        this.delConfirm(record);
        break;
      default:
    }
  };

  delConfirm = record => {
    const { dispatch } = this.props;
    this.confirmModal = Modal.confirm({
      title: `删除确认`,
      content: `提示：删除后不可恢复!`,
      okButtonProps: { type: 'danger' },
      style: { top: '20%' },
      okText: '确定',
      onOk: () => {
        return new Promise(resolve => {
          this.confirmModal.update({
            okButtonProps: { type: 'primary', loading: true },
            cancelButtonProps: { disabled: true },
          });
          dispatch({
            type: 'priceManger/del',
            payload: {
              id: record.id,
            },
            callback: res => {
              if (res.success) {
                resolve();
                this.reloadData();
              } else {
                this.confirmModal.update({
                  okButtonProps: { loading: false },
                  cancelButtonProps: { disabled: false },
                });
              }
            },
          });
        });
      },
      cancelText: '取消',
      onCancel: () => {
        this.confirmModal.destroy();
        this.confirmModal = null;
      },
    });
  };

  handlerCancel = needRefresh => {
    const { dispatch } = this.props;
    dispatch({
      type: 'priceManger/updateState',
      payload: {
        showCreate: false,
        showUpdate: false,
        showView: false,
        showPassWord: false,
      },
    });
    if (needRefresh) {
      this.reloadData();
    }
  };

  render() {
    const { priceManger } = this.props;
    const { showView, showUpdate, currentData, showCreate } = priceManger;
    const columns = [
      {
        title: formatMessage({ id: 'global.operation', defaultMessage: '操作' }),
        key: 'operation',
        width: 100,
        align: 'center',
        dataIndex: 'id',
        className: 'action',
        required: true,
        render: (id, record) => (
          <span className={cls('action-box')}>
            <ExtAction key={id} onAction={this.handlerAction} recordItem={record} />
          </span>
        ),
      },
      {
        title: '类型',
        dataIndex: 'name0',
        width: 200,
        required: true,
      },
      {
        title: '品牌',
        dataIndex: 'name1',
        width: 200,
        required: true,
      },
      {
        title: '系列',
        dataIndex: 'name2',
        width: 200,
        required: true,
      },
      {
        title: '型号',
        dataIndex: 'name3',
        width: 200,
        required: true,
      },
      {
        title: '规格',
        dataIndex: 'name4',
        width: 200,
        required: true,
      },
      {
        title: '成色',
        dataIndex: 'name5',
        width: 200,
        required: true,
      },
      {
        title: '调价幅度',
        dataIndex: 'priceUpdate',
        width: 200,
        required: true,
      },
    ];
    const toolBarProps = {
      left: (
        <>
          <Button
            key={PRICE_MANGER_ACTION.ADD}
            type="primary"
            onClick={this.add}
            icon="plus"
            ignore="true"
          >
            <FormattedMessage id="global.add" defaultMessage="新建" />
          </Button>
          <Button onClick={this.reloadData}>
            <FormattedMessage id="global.refresh" defaultMessage="刷新" />
          </Button>
        </>
      ),
    };
    const extTableProps = {
      bordered: false,
      toolBar: toolBarProps,
      columns,
      storageId: '001',
      onTableRef: ref => (this.tableRef = ref),
      showSearch: false,
      remotePaging: true,
      searchPlaceHolder: '输入名称关建字查询',
      searchWidth: 220,
      showSearchTooltip: true,
      searchProperties: ['userName', 'account'],
      store: {
        type: 'POST',
        url: `${SERVER_PATH}/jiyu/jyPriceUpdate/findByPage`,
      },
      sort: {
        field: { createdDate: 'desc' },
      },
    };

    return (
      <div className={cls(styles['container-box'])}>
        <ExtTable {...extTableProps} />

        {showCreate ? (
          <Suspense fallback={<Loader />}>
            <CreateModal onCloseModal={this.handlerCancel} onSave={this.onSave} />
          </Suspense>
        ) : null}
        {showUpdate ? (
          <Suspense fallback={<Loader />}>
            <UpdateModal
              onCloseModal={this.handlerCancel}
              onSave={this.onSave}
              currentData={currentData}
            />
          </Suspense>
        ) : null}
        {showView ? (
          <Suspense fallback={<Loader />}>
            <ViewModal onCloseModal={this.handlerCancel} currentData={currentData} />
          </Suspense>
        ) : null}
      </div>
    );
  }
}

export default PriceManger;
